package com.xinnet.mms.customtransfer.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.xinnet.core.utils.ConfigUtil;
import com.xinnet.mms.allot.service.CustomAllotService;
import com.xinnet.mms.common.AppGlobalContainer;
import com.xinnet.mms.customerManage.dao.CustomerManageDao;
import com.xinnet.mms.customerstate.dao.CustomerStateHistDao;
import com.xinnet.mms.customtransfer.service.SecondDevelopCustomTransferService;
import com.xinnet.mms.empcustomrelation.dao.EmpCustomRelationDao;
import com.xinnet.mms.entity.CustomStateHist;
import com.xinnet.mms.entity.Customer;
import com.xinnet.mms.entity.CustomerCare;
import com.xinnet.mms.entity.EmpCustomRelation;
import com.xinnet.mms.entity.Product;
import com.xinnet.mms.entity.PublicConfig;
import com.xinnet.mms.order.dao.OrderDao;
import com.xinnet.mms.product.dao.ProductDao;
import com.xinnet.mms.utils.CustomerManage;
import com.xinnet.mms.utils.CustomerType;

@Service("secondDevelopCustomTransferService")
public class SecondDevelopCustomTransferServiceImpl implements SecondDevelopCustomTransferService{
	@Autowired
	private CustomAllotService customAllotService;
	@Autowired
	private CustomerManageDao customerManageDao;
	@Autowired
	private CustomerStateHistDao customerStateHistDao;
	@Autowired
	private EmpCustomRelationDao empCustomRelationDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private ProductDao productDao;
	
	private static Logger log=LoggerFactory.getLogger(SecondDevelopCustomTransferServiceImpl.class);
	
	/**
	 * 二次开发客户流转
	 */
	public void secondDevelopCustomTransfer() throws Exception{
		//获取产品规则
		Map<String,Product> productRuleMap = AppGlobalContainer.productRuleMap;
		if(productRuleMap==null || productRuleMap.isEmpty()){
			return;
		}
		//获取二次开发客户
		Map<Integer,List<EmpCustomRelation>> customerMap = (Map<Integer,List<EmpCustomRelation>>)AppGlobalContainer.transferCustomMap;
		if(customerMap==null || customerMap.isEmpty()){
			return;
		}
		List<EmpCustomRelation> secondDevelopCustomList = customerMap.get(CustomerType.TWICE_CUSTOMER);
		if(secondDevelopCustomList==null || secondDevelopCustomList.isEmpty()){
			log.info("二次开发客户为空");
			return;
		}
        String isTest = ConfigUtil.getString("isTest");
        if(isTest==null || "".equals(isTest)){
        	log.error("配置异常：是否是测试环境");
        	return;
        }
        log.info("************************************************************************************二次开发客户流转开始********************************************");
		//流转操作
		for(int i=0;i<secondDevelopCustomList.size();i++){
			EmpCustomRelation secondDevelopCustom = secondDevelopCustomList.get(i);
			this.customTransferForSecondDevelopCustomer(secondDevelopCustom, isTest);
		}	
		secondDevelopCustomList=null;
		log.info("************************************************************************************二次开发客户流转开始********************************************");
	}
	
	
	/**
	 * 对每个二次开发客户流转
	 * @param newRegisterCustom
	 * @param isTest
	 * @param transferRuleList
	 * @throws Exception
	 */
	@Transactional(propagation=Propagation.REQUIRES_NEW,readOnly=false,rollbackFor=Exception.class)
	public void customTransferForSecondDevelopCustomer(EmpCustomRelation secondDevelopCustom,String isTest){
		String  customId = secondDevelopCustom.getCustomId();
		try {
			Customer tempCustomer = customAllotService.getCustomerById(secondDevelopCustom.getCustomId());
			String empNo = secondDevelopCustom.getEmpId();
			String productCode = secondDevelopCustom.getProductCode();
			String productId = secondDevelopCustom.getProductId();
			if(productId==null || "".equals(productId)){
				log.info("当前产品ID: is null  return");
				return;
			}
			if(productCode==null || "".equals(productCode)){
				log.info("当前产品CODE: is null  return");
				return;
			}
			String regionalId = secondDevelopCustom.getRegionalId();
			String companyId = tempCustomer.getCompanyId();
			Date pushDate = secondDevelopCustom.getCreateTime();
			String pushHistId = secondDevelopCustom.getPushHistId();
			//获取当前产品规则
			Product currentProductRule=AppGlobalContainer.productRuleMap.get(productId);
			if(currentProductRule==null){
				log.error("当前产品规则为空!"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
				return;
			}
			
			//获取订单
			//获取订单
			Date buyDate = null;
			Date dueDate = null;
			Map<String,CustomerCare> customerCareMap =AppGlobalContainer.customerCareMap;
			CustomerCare customerCare = customerCareMap.get(empNo+"_"+productCode);
			if(customerCare!=null){
				Date tempBuyDate = customerCare.getBuyDate();
				Date tempDueDate = customerCare.getDueTime();
				if(tempBuyDate==null || tempDueDate==null){
					SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String transferTime = sdf.format(new Date());
					log.error("订单数据异常：购买日期为空或结束日期为空。删除客户ID为："+customId+" 数据  "+transferTime);
					return;
				}
				buyDate = tempBuyDate;
				dueDate = tempDueDate;
			}else{
				Map<String,CustomerCare> delCustomerCareMap =AppGlobalContainer.delCustomerCareMap;
				CustomerCare delCustomerCare = delCustomerCareMap.get(empNo+"_"+productCode);
				
				if(delCustomerCare!=null){
					Date tempBuyDate = delCustomerCare.getBuyDate();
					Date tempDueDate = delCustomerCare.getDueTime();
					if(tempBuyDate==null || tempDueDate==null){
						SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
						String transferTime = sdf.format(new Date());
						log.error("订单数据异常：购买日期为空或结束日期为空。删除客户ID为："+customId+" 数据  "+transferTime);
						return;
					}	
					buyDate = tempBuyDate;
					dueDate = tempDueDate;
				}else{
					SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					String transferTime = sdf.format(new Date());
					log.error("订单数据异常：没有此订单。删除客户ID为："+customId+" 数据  "+transferTime);
					return;
				}
			}
			Date currentDate = new Date();
			if(currentDate.before(dueDate)){
				if(pushDate==null){
					return;
				}
				//二次开发未成交停留时间（日）
				Integer holdTime = currentProductRule.getRedevNodealholdtime();
				//Integer sysPushHoldTime = currentProductRule.getSysallocationNodealholdtime();
				//二次开发停顿时间（日）
				Integer stopTime = currentProductRule.getMiddleServiceCycle();
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(pushDate);
				if("true".equals(isTest)){
					calendar.add(Calendar.MINUTE, holdTime);
					calendar.add(Calendar.MINUTE, stopTime);
				}else if("false".equals(isTest)){
					calendar.add(Calendar.DATE, holdTime);	
					calendar.add(Calendar.DATE, stopTime);
				}else{
					log.info("环境异常  是否测试  return");
					return;
				}
				Date pushTime = calendar.getTime();
				//推送时间
				if(currentDate.after(pushTime)){
					Map<String,List<CustomStateHist>> customStateHistMap = AppGlobalContainer.customStateHistMap;
					List<CustomStateHist> customStateHistList = customStateHistMap.get(customId);
					Product pushProduct = AppGlobalContainer.getPushProduct(currentProductRule,customStateHistList);
					if(pushProduct!=null){
						String pushProductName = pushProduct.getProductName();
						String pushProductCode =  pushProduct.getProductCode();
						String pushProductId = pushProduct.getId();
						//获取可用的业绩保留期
						Map<String,PublicConfig> scoreHoldDateMap = AppGlobalContainer.scoreHoldDateMap;
						PublicConfig  publicConfig = scoreHoldDateMap.get("scoreHoldTime");
						String scoreHoldTime = publicConfig.getConfigValue();
						
						List<CustomStateHist> tempCustomStateHistList = customerStateHistDao.getCustomStateHistByScoreHoldTimeAndCustomIdAndProductId(customId,scoreHoldTime,pushProductId);
						if(tempCustomStateHistList!=null && tempCustomStateHistList.size()>0){
							customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
							CustomStateHist tempCustomStateHist = tempCustomStateHistList.get(0);
							
							String empId = tempCustomStateHist.getEmpId();
							
							Customer secondDevelopCustomer = new Customer();
							secondDevelopCustomer.setEmpno(empId);
							secondDevelopCustomer.setCusId(customId);
							secondDevelopCustomer.setProductLabel(pushProductCode);
							secondDevelopCustomer.setProductId(pushProductId);
							secondDevelopCustomer.setProductName(pushProductName);
							secondDevelopCustomer.setRegionalId(regionalId);
							secondDevelopCustomer.setCompanyId(companyId);
							secondDevelopCustomer.setCustomerType(CustomerManage.TWICE_CUSTOMER);

							secondDevelopCustomer.setPushHistId(pushHistId);
							//系统推送
							customAllotService.allot(secondDevelopCustomer,CustomerManage.TWICE_CUSTOMER);	
						}else{
							Customer secondDevelopCustomer = new Customer();
							secondDevelopCustomer.setCusId(customId);
							secondDevelopCustomer.setProductLabel(pushProductCode);
							secondDevelopCustomer.setProductId(pushProductId);
							secondDevelopCustomer.setProductName(pushProductName);
							secondDevelopCustomer.setRegionalId(regionalId);
							secondDevelopCustomer.setCompanyId(companyId);
							secondDevelopCustomer.setCustomerType(CustomerManage.TWICE_CUSTOMER);
							//系统推送
							customAllotService.allot(secondDevelopCustomer,CustomerManage.TWICE_CUSTOMER);	
							empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
							customerStateHistDao.updateCustomStateHistByPushHistId(pushHistId);
						}
					}
				}
			}else{
				//客户已到期,判断是否进入公海时间	(是否有其它产品在服务期，没有进公海)
				Integer endServiceGoOpenSea = currentProductRule.getGoOpenseaTime();//服务期后进公海
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(buyDate);
				calendar.add(Calendar.DATE,endServiceGoOpenSea);
				Date goOpenSeaDate = calendar.getTime();//服务期后进公海时间
				if(currentDate.after(goOpenSeaDate)){
					 List<Product>  productList = productDao.queryEnableProduct();
					 if(productList!=null){
						 boolean isCanGoOpenSea =true;
						 for (Iterator<Product> iterator2 = productList.iterator(); iterator2.hasNext();) {
							Product product = (Product) iterator2.next();
							String id = product.getId();
							Integer tempEndServiceGoOpenSea = product.getGoOpenseaTime();//服务期后进公海
							String tempProductCode1 = product.getProductCode();
							if(!id.equals(productId)){
								List<CustomerCare> tempCustomerCareList =orderDao.getOrdersByCusIdAndProductCode(customId, tempProductCode1);
								if(tempCustomerCareList!=null &&tempCustomerCareList.size()>0){
									for (Iterator<CustomerCare> iterator3 = tempCustomerCareList.iterator(); iterator3.hasNext();) {
										CustomerCare customerCare2 = (CustomerCare) iterator3.next();
										Date tempDueTime = customerCare2.getDueTime();
										Calendar tempCalendar = Calendar.getInstance();
										tempCalendar.setTime(tempDueTime);
										tempCalendar.add(Calendar.DATE,tempEndServiceGoOpenSea);
										Date tempGoOpenSeaDate = calendar.getTime();
										if(currentDate.before(tempGoOpenSeaDate)){
											isCanGoOpenSea=false;
											break;
										}
									}
								}
							}
						}
						if(isCanGoOpenSea){
							empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
							customerStateHistDao.updateCustomStateHistByCustomIdAndEmpNo(customId,empNo,productId);
							//进入公海
							Customer customer = new Customer();
							customer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
							customer.setCusId(customId);
							customer.setIsBuy(CustomerManage.BUY_YES);
							customerManageDao.goOpenSea(customer);
							customAllotService.allot(customer, CustomerManage.OPEN_SEA_CUSTOMER);
							log.info("二次开发进入公海：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
						}	 
					 }else{
						 empCustomRelationDao.delEmpCustomRelationByCustomIdAndEmpNo(customId,empNo,productCode);
						customerStateHistDao.updateCustomStateHistByCustomIdAndEmpNo(customId,empNo,productId);
						//进入公海
						Customer customer = new Customer();
						customer.setCustomerType(CustomerManage.OPEN_SEA_CUSTOMER);
						customer.setCusId(customId);
						customer.setIsBuy(CustomerManage.BUY_YES);
						customerManageDao.goOpenSea(customer);
						customAllotService.allot(customer, CustomerManage.OPEN_SEA_CUSTOMER);
						log.info("二次开发客户进入公海：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
					 }
				}
			}
		} catch (Exception e) {
			log.error("二次开发客户流转异常：customer id"+customId+"  "+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),e);
		}
		
		
	}
	
	/**
	 * 获取订单假数据 用于测试
	 * @return
	 * @throws ParseException
	 */
	private List<CustomerCare> getCustomerCareListForTest() throws ParseException{
		List<CustomerCare> customerCareList = new ArrayList<CustomerCare>();
		List<EmpCustomRelation> empCustomRelationList = null;//empCustomRelationDao.getTransferCustom();
		
		for (Iterator<EmpCustomRelation> iterator = empCustomRelationList.iterator(); iterator.hasNext();) {
			EmpCustomRelation empCustomRelation = (EmpCustomRelation) iterator.next();
			String customId = empCustomRelation.getCustomId();
			
			String productId = empCustomRelation.getProductId();
			
			CustomerCare customerCare = new CustomerCare();
			customerCare.setProductId(productId);
			customerCare.setCusId(customId);
			SimpleDateFormat sdf =  new SimpleDateFormat("yyyy-MM-dd");
			java.util.Date utilBuyDate = sdf.parse("2013-05-01"); 
			java.sql.Date buyDate=new java.sql.Date (utilBuyDate.getTime());
			
			java.util.Date utilDueTime = sdf.parse("2014-06-31"); 
			java.sql.Date dueTime=new java.sql.Date (utilDueTime.getTime());

			customerCare.setBuyDate(buyDate);
			customerCare.setDueTime(dueTime);
			customerCareList.add(customerCare);
		}
		return customerCareList;
	}
}
